import CryptoJS from "crypto-js";

const debugLog = console.log;
/**
 * 解析音频数据
 * @param {File} file 文件对象
 * @returns {Promise<{duration:number}>} 返回解析出来的音频信息
 */
const analysisAudioObj = new Audio();
export function analysisAudio(file) {
    debugLog("== 解析音频数据中 ==");
    const filePath = URL.createObjectURL(file);
    // const audio = new Audio(filePath);
    analysisAudioObj.src = filePath;
    return new Promise((resolve) => {
        analysisAudioObj.onloadedmetadata = () => {
            const returnBody = {
                duration: Math.ceil(analysisAudioObj.duration),
            };
            debugLog("== 解析音频数据成功; %s ==", JSON.stringify(returnBody));
            resolve(returnBody);
            analysisAudioObj.src = "";
            URL.revokeObjectURL(filePath);// 销毁blob
        };
    });
}

export function computedSign(file) {
    debugLog("== 计算音频签名中 ==");
    const suffix = file.name.slice(file.name.lastIndexOf(".") + 1); // 切出文件后缀名
    const SHA256 = CryptoJS.SHA256(`${Date.now()}-${file.name}`).toString();
    const sign = `${suffix}-${SHA256}.${suffix}`; // mp3-84e7d39e0bd8ca733471cac2e53d0efc44ba29b0289b516efe4bc23b905c3354.mp3
    debugLog("== 音频签名计算成功: %s ==", sign);
    return sign;
}

export function formatFiles(file) {
    const name = file.name.slice(0, file.name.lastIndexOf("."));
    const fileData = {
        rid: 0,
        path: "",
        cover: "",
        name,
        artist: "",
        mark: "",
        lyric: "",
        size: file.size,
        file, // 文件流
        progress: 0, // 上传进度
        isError: false, // 是否上传失败,
        selfHide: false,
        tip: 0,
    };
    return fileData;
}

/**
    * 验证音频文件格式
    * @param {File} file 文件对象
    * @returns {boolean} 验证结果
    */
export function verifyAudioFileMime(file) {
    const acceptMimeTyep = ["audio/mpeg", "audio/mp3", "audio/ogg", "audio/wav"];
    return acceptMimeTyep.indexOf(file.type) !== -1;
}
